<?php

namespace app\modules\m\controllers;

use yii\web\Controller;
use \app\modules\m\controllers\common\BaseController;
use \app\common\services\UrlService;
use \app\common\services\weixin\RequestServices;
use \app\common\components\HttpCurl;
class OauthController extends BaseController{
	//微信登录
    public function actionLogin(){
    	$config=\Yii::$app->params['weixin'];
    	$appid=$config['appid'];
    	$redirect_uri=UrlService::buildMUrl("/oauth/callback");
    	$redirect_uri=urlencode($redirect_uri);
    	$scope=$this->get("scope","snsapi_base");
    	$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'#wechat_redirect';
    	// echo $url;
    	// exit;
    	return $this->redirect($url) ;
    }
    public function actionCallback(){
    	$session=\Yii::$app->session;
    	$code=$this->get('code',"");
    	//如果session中有用户的信息则直接返回
    	if( isset($session['userinfo']['access_token']) && $session['userinfo']['expired_time']>=time() ){
    		echo '123';
    		var_dump($session['userinfo']);
    		die;
    		
    	}
    	if(!$code){
    		$this->goHome();
    	}
    	$config=\Yii::$app->params['weixin'];
    	$appid=$config['appid'];
    	$sk=$config['sk'];
    	$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$sk&code=$code&grant_type=authorization_code";
    	$res=HttpCurl::get($url);
    	$res=json_decode($res,true);
    	$res['expired_time']=time()+7000;
    	
    	$session->set("userinfo",$res);

    	//拉取用户信息
    	$scope=isset($res['scope'])?$res['scope']:"";
    	$access_token=isset($res['access_token'])?$res['access_token']:"";
    	$openid=isset($res['openid'])?$res['openid']:"";
    	
    	if($scope=="snsapi_userinfo"){
    		$url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
    		$res=HttpCurl::get($url);
    	}
    	var_dump($res);

    	return "i am back";
    }
}
